package com.luych.toolbox.automation.service.core.executor;

import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;
import com.luych.toolbox.automation.service.core.connection.SshConnection;
import com.luych.toolbox.common.service.tool.Cmd;
import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.function.Consumer;

public class BashExecutor implements TaskExecutor<SshConnection> {

    private static final Logger LOGGER = LoggerFactory.getLogger(Cmd.class);

    private final String script;
    private Consumer<String> stdout = LOGGER::info;
    private Consumer<String> stderr = LOGGER::warn;

    public BashExecutor(String script) {
        this.script = script;
    }

    public void setStdout(Consumer<String> stdout) {
        this.stdout = stdout;
    }

    public void setStderr(Consumer<String> stderr) {
        this.stderr = stderr;
    }

    @Override
    public String execute(SshConnection server, String... args) {
        String file = "/tmp/" + RandomStringUtils.randomAlphanumeric(10);
        try {
            Cmd.uploadRemote(server.getHost(), server.getPort(), server.getUser(), server.getPass(),
                    new ByteArrayInputStream(script.getBytes(StandardCharsets.UTF_8)), file);
            return Cmd.executeRemote(server.getHost(), server.getPort(), server.getUser(), server.getPass(),
                    "bash " + file + " " + String.join(" ", args), stdout, stderr);
        } catch (JSchException | SftpException | InterruptedException | IOException e) {
            throw new RuntimeException(e);
        }
    }
}
